package com.bw.interceptor;

import com.alibaba.fastjson.JSON;

import io.jsonwebtoken.Jwt;
import org.spring.kun.common.JwtUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 默认全部拦截
//        boolean b = false;
        // 从request中获取 cookie    浏览器发过来的

//        Cookie[] cookies = request.getCookies();
//
//        if (cookies != null) {  // 从众多的cookie中过滤出 令牌token
//            System.out.println("cookie:" + JSON.toJSONString(cookies));
//            for (Cookie cookie : cookies) {
//                String name = cookie.getName();
//                if (name.equals("token")) {
//                    String token = cookie.getValue();
//                    // 验证令牌是否有效
//                    b = JwtUtils.validToken(token);
//                }
//            }
//        }


        // 从request中 获取cookie 并从cookie中 过滤 token
        String token = TokenUtils.getTokenFromRequest(request);
        // 验证token是否有效
        boolean b = JwtUtils.validToken(token);


        if (!b) {
            response.sendRedirect("/loginPage.do");
            return false;

        }


        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
